package org.liushengpei.com.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * 配置ReturnCallBack(每个RabbitTemplate只能配置一个ReturnCallBack)
 */
@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取RabbitTemplate的bean
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        //消息成功发送到交换机，但是发送到队列失败
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            //消息
            Message message = returnedMessage.getMessage();
            int replyCode = returnedMessage.getReplyCode();
            //交换机
            String exchange = returnedMessage.getExchange();
            //路由键
            String routingKey = returnedMessage.getRoutingKey();
            String replyText = returnedMessage.getReplyText();
            log.error("message=" + message + ",replyCode=" + replyCode + ",exchange=" + exchange + ",routingKey=" + routingKey + ",replyText=" + replyText);
        });
    }
}
